package com.paas.demo.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class NettyClient {
    private  int port;
    private  String address;

    public NettyClient(int port,String address) {
        this.port = port;
        this.address = address;
    }
    public void start(){
        EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer(){
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast("idleStateHandler",
                                new IdleStateHandler(30, 0, 0, TimeUnit.MINUTES));
                        //关闭日志
                        ch.pipeline().addLast(new Decoder4LoggingOnly());
                        // 1024表示单条消息的最大长度，解码器在查找分隔符的时候，达到该长度还没找到的话会抛异常
                        // 0x7e 分隔符
						/*
						ch.pipeline().addLast(
								new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(new byte[] { 0x7e }),
										Unpooled.copiedBuffer(new byte[] { 0x7e, 0x7e })));
										*/
                        ch.pipeline().addLast(new TCPClientHandler());
                    }
                });

        try {
            ChannelFuture future = bootstrap.connect(address,port).sync();
            future.channel().closeFuture().sync();

            System.out.println("NettyClient connect success .");

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        NettyClient client = new NettyClient(8088, "192.168.8.44");
        client.start();
    }
}
